from django.forms import model_to_dict
from django.shortcuts import render
import datetime
import logging
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from pymysql import MySQLError
from post.forms import PostForm
from post.models import Post
from users.models import UserProfile, Focus
from users.user_utils import check_token
from .serializes import PostSerializer, AllPostSerializer


@csrf_exempt
def get_my_post(request):
    code = 0
    msg = 'ok'
    data = 0
    if request.method == 'GET':
        token = request.GET.get('token', None)
        user_id = check_token(token)
        if user_id:
            user = UserProfile.objects.filter(id=user_id).first()
            if user:
                my_post = PostSerializer(Post.objects.filter(author_id=user.id).all(), many=True)
                data = my_post.data
            else:
                code = 10000
                msg = "不存在该用户"
        else:
            code = 10000
            msg = "无效的令牌"
    else:
        code = 10000
        msg = "请求方法错误"
    return JsonResponse({
        'code': code,
        'msg': msg,
        'data': data
    })


def delete_post(request, post_id):
    code = 0
    msg = 'ok'
    data = 0
    if request.method == 'GET':
        token = request.GET.get('token', None)
        user_id = check_token(token)
        if user_id:
            user = UserProfile.objects.filter(id=user_id).first()
            if user:
                try:
                    post = Post.objects.filter(id=post_id).first()
                    post.is_delete = True
                    post.delete_time = datetime.datetime.now()
                    post.save()
                    data = 1
                except MySQLError:
                    code = 30000
                    msg = "服务器错误"
            else:
                code = 10000
                msg = "不存在该用户"
        else:
            code = 10000
            msg = "无效的令牌"
    else:
        code = 10000
        msg = "请求方法错误"
    return JsonResponse({
        'code': code,
        'msg': msg,
        'data': data
    })


@csrf_exempt
def pub_post(request):
    code = 0
    msg = 'ok'
    data = 0
    if request.method == 'POST':
        token = request.POST.get('token', None)
        user_id = check_token(token)
        if user_id:
            user = UserProfile.objects.filter(id=user_id).first()
            if user:
                title = request.POST.get('title', None)
                content = request.POST.get('content', None)
                images = request.FILES.get('images', None)
                post_form = PostForm({"title": title, "content": content})
                # post_form.title = title
                # post_form.content = content
                if post_form.is_valid():
                    try:
                        post = Post()
                        post.author = user
                        post.title = title
                        post.content = content
                        if images:
                            post.images = images
                        post.save()
                        data = 1
                    except MySQLError as e:
                        logging.error(e)
                        code = 30000
                        msg = "服务器出了点小差错"
                else:
                    code = 10000
                    msg = post_form.errors.as_json()
                    print(msg)
            else:
                code = 10000
                msg = "不存在该用户"
        else:
            code = 10000
            msg = "无效的令牌"
    else:
        code = 10000
        msg = "请求方法错误"
    return JsonResponse({
        'code': code,
        'msg': msg,
        'data': data
    })


# nizhanzhao
def get_all_post(request):
    '''
    获取动态列表
    :param request:
    :return:
    '''
    post = Post.objects.all()
    serializer = AllPostSerializer(post, many=True)
    data = {
        'code': 0,
        'msg': 'ok',
        'data': serializer.data
    }
    return JsonResponse(data, safe=False)

@csrf_protect
def get_focus_people_post(request,id):
    '''
    获取关注人的列表
    :param request:
    :return:
    '''
    token = request.GET.get('token',None)
    print(token)
    t = check_token(token)
    if t:
        name = UserProfile.objects.filter(id = id).first()
        focus = Focus.objects.filter(user_id_a=name.id)
        data1 = []
        code = 0
        msg = 'ok'
        for f in focus:
            # print(f.user_id_b.name)
            post = Post.objects.filter(author=f.user_id_b)
            for post in post:
                dict2 = {
                    'focus_name': f.user_id_b.name,
                    'post': model_to_dict(post)
                }
                data1.append(dict2)
        # print(data1)
        # return HttpResponse('1111111')
    else:
        code = '10000'
        msg = '令牌过期'
        data1 = []
    data = {
        'code': code,
        'msg': msg,
        'data': data1,
    }
    return JsonResponse(data, safe=False)

def get_post_detail(request):
    '''
    获取动态详情
    :param request:
    :return:
    '''
    post = Post.objects.all().values('id', 'title', 'content' ,'author', 'add_time', 'praise_count')
    data = {
        'code': 0,
        'msg': 'ok',
        'data': list(post)
    }
    return JsonResponse(data, safe=False)



